package com.example.mybatisplusdemo.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * @author H
 * @date 2022/12/10
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(List.class)
@Component
public class ListVarcharHandler extends BaseTypeHandler<List<Integer>> {

    /**
     * 设置非空数据参数
     * @param preparedStatement
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Integer> parameter, JdbcType jdbcType) throws SQLException {
        System.out.println("setNonNullParameter...");
        StringJoiner sj = new StringJoiner(",");
        if (parameter != null) {
            for (Integer par : parameter) {
                sj.add(String.valueOf(par));
            }
        }
        preparedStatement.setString(i, sj.toString());
    }

    /**
     * 通过列名读取数据
     * @param resultSet
     * @param columnName
     * @return
     * @throws SQLException
     */
    @Override
    public List<Integer> getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        System.out.println("根据列名");
        return Arrays.stream(resultSet.getString(columnName).split(",")).map(Integer::parseInt).collect(Collectors.toList());
    }

    /**
     * 通过下标读取数据
     * @param resultSet
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public List<Integer> getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        System.out.println("根据列索引号");
        return Arrays.stream(resultSet.getString(columnIndex).split(",")).map(Integer::parseInt).collect(Collectors.toList());
    }

    /**
     * 通过存储过程读取数据
     * @param callableStatement
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public List<Integer> getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        System.out.println("getNullableResult...");
        return Arrays.stream(callableStatement.getString(columnIndex).split(",")).map(Integer::parseInt).collect(Collectors.toList());
    }
}
